package com.example.demo.config;

import com.example.demo.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.sql.DataSource;

/**
 * @author void
 * @date 2021/1/5 15:38
 * @desc
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailService myUserDetailService;
    @Autowired
    private DataSource dataSource;

    /**
     * 方案一
     * @param http
     * @throws Exception
     */
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests()
//                .antMatchers("/admin/api/**").hasRole("ADMIN")
//                .antMatchers("/user/api/**").hasRole("USER")
//                .antMatchers("/app/api/**").permitAll()
//                .anyRequest().authenticated()
//                .and().csrf().disable().formLogin()
//                //使用记住密码功能必须实现userDetailsService 不然关闭浏览器重新登录会error
//                .and().rememberMe().userDetailsService(myUserDetailService).key("void");
//                // key的作用是cookie加密的随机字符串，不指定默认uuid，服务重启原本cookie都失效，制定了重启服务以前cookie还可以使用
//    }

    /**
     * 方案二
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        JdbcTokenRepositoryImpl impl = new JdbcTokenRepositoryImpl();
        impl.setDataSource(dataSource);
        
        http.authorizeRequests()
                .antMatchers("/admin/api/**").hasRole("ADMIN")
                .antMatchers("/user/api/**").hasRole("USER")
                .antMatchers("/app/api/**").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable().formLogin()
                //使用记住密码功能必须实现userDetailsService 不然关闭浏览器重新登录会error
                .and().rememberMe().userDetailsService(myUserDetailService).tokenRepository(impl);
    }
}
